<?php

namespace adminApi\modules\rbac\controllers;

use adminApi\modules\rbac\models\Adminers;
use Carbon\Carbon;
use common\components\fast_api\Controller;
use common\components\wtools\tools\ArrayHelper;
use common\components\wtools\tools\Model;
use common\components\wtools\validators\Mobile;
use common\components\wtools\validators\Password;
use common\components\wtools\validators\Username;
use common\datas\Enums;
use common\Tools;
use yii\base\DynamicModel;
use yii\data\ActiveDataProvider;

class AdminerController extends Controller
{
    /**
     * 获取当前管理员信息
     * @desc 获取当前管理员信息
     * @return mixed
     */
    public function actionAuthInfo()
    {
        /** @var Adminers $adminer */
        $adminer = \Yii::$app->user->identity;
        return $this->apiSuccess([
            'adminerInfo' => [
                'created_at' => $adminer->created_at,
                '_created_at' => Tools::toDate($adminer->created_at),
                'updated_at' => $adminer->updated_at,
                '_updated_at' => Tools::toDate($adminer->updated_at),
                'mobile' => $adminer->mobile,
                'account_name' => $adminer->account_name,
                'status' => $adminer->status,
                'is_super' => $adminer->is_super,
            ],
            'permissionPaths' => $adminer->permissionPaths,
        ]);
    }

    /**
     * 管理员是否有权限
     * @desc 权限识别
     * @param string $permission 权限
     * @return array
     */
    public function actionIsAuthPermission($permission)
    {
        $can = Enums::NO;
        /** @var Adminers $adminer */
        $adminer = \Yii::$app->user->identity;
        if ($adminer->is_super === Enums::YES) {
            $can = Enums::YES;
        } else {
            $permissionPaths = $adminer->permissionPaths;
            if (in_array($permission, $permissionPaths)) {
                $can = Enums::YES;
            }
        }
        $authInfo = [];
        if ($can === Enums::YES) {
            $jwtData = $adminer->generateJwtTokenData();
            $authInfo = \Yii::$app->adminApiTool->setJwtTokenData($jwtData)->post('/rbac/adminer/auth-info');
        }
        return $this->apiSuccess([
            'can' => $can,
            'authInfo' => $authInfo,
        ]);
    }

    /**
     * 列表
     * @desc 管理员列表
     * @param int $page 页码
     * @param int $pageSize 每页条数
     * @param string|null $account_name 账号
     * @param string|null $mobile 手机号
     * @return mixed
     * @throws \yii\base\InvalidConfigException
     */
    public function actionList($page = 1, $pageSize = 10, $account_name = null, $mobile = null, $status = null)
    {
        $query = Adminers::find()->andWhere(['is_super' => Enums::NO]);
        if ($account_name) {
            $query->andFilterWhere(['like', 'account_name', $account_name]);
        }
        if ($mobile) {
            $query->andFilterWhere(['like', 'mobile', $mobile]);
        }
        if ($status) {
            $query->andFilterWhere(['status' => $status]);
        }
        $apiPageData = $this->apiPageData($query, $page, $pageSize);
        $items = [];
        foreach ($apiPageData->dataProvider->models as $k => $v) {
            /** @var Adminers $v */
            $m = [];
            $m['id'] = $v->id;
            $m['account_name'] = $v->account_name;
            $m['mobile'] = $v->mobile;
            $m['created_at'] = $v->created_at;
            $m['_created_at'] = date("Y-m-d H:i", $v->created_at);
            $m['status'] = $v->status;
//            $m['status'] = (string)$v->status;
            $m['_status'] = Enums::getStatusDesc()[$v->status];
            $items[] = $m;
        }
        $data = [
            'items' => $items,
            '_meta' => $apiPageData->meta,
        ];
        return $this->apiSuccess($data, '获取列表成功');
    }

    /**
     * 添加or修改管理员
     * @desc post
     * @param string $mobile
     * @param string $account_name
     * @param int $status
     * @param string $password
     * @param int $id
     * @return array
     */
    public function actionAddOrEdit($mobile, $account_name, $status, $password = '', $id = 0)
    {
        $rules = [
            [['mobile', 'account_name', 'status'], 'required'],
            [['mobile', 'account_name', 'status', 'password'], 'trim'],
            ['status', 'in', 'range' => array_keys(Enums::getStatusDatas())],
            ['mobile', Mobile::class],
            ['account_name', Username::class],
            ['password', Password::class],
        ];
        if ($id > 0) {
            $adminer = Adminers::findOne($id);
            $rules = ArrayHelper::merge($rules, [
                ['mobile', 'unique', 'targetClass' => Adminers::class, 'targetAttribute' => 'mobile', 'message' => '该手机号已存在', 'filter' => ['<>', 'id', $id]],
                ['account_name', 'unique', 'targetClass' => Adminers::class, 'targetAttribute' => 'account_name', 'message' => '该账号已存在', 'filter' => ['<>', 'id', $id]],
            ]);
        } else {
            $adminer = new Adminers();
            $adminer->auth_key = Tools::generateHasDateUniqueString();
            $adminer->generateToken();
            $rules = ArrayHelper::merge($rules, [
                ['password', 'required'],
                ['mobile', 'unique', 'targetClass' => Adminers::class, 'targetAttribute' => 'mobile', 'message' => '该手机号已存在。'],
                ['account_name', 'unique', 'targetClass' => Adminers::class, 'targetAttribute' => 'account_name', 'message' => '该账号已存在。'],
            ]);
        }
        $model = DynamicModel::validateData(['mobile' => $mobile, 'account_name' => $account_name, 'status' => $status, 'password' => $password], $rules);
        if (!$model->validate()) {
            return $this->apiError(Model::getModelError($model));
        }
        $adminer->mobile = $model->mobile;
        $adminer->account_name = $model->account_name;
        $adminer->status = $model->status;
        if ($model->password) {
            $adminer->generatePassword($model->password);
        }
        if (!$adminer->save()) {
            return $this->apiError(Model::getModelError($adminer));
        }
        return $this->apiSuccess([
            'adminer' => $adminer,
        ], "保存成功");
    }
}
